package databases

import (
	"errors"
	"github.com/go-xorm/xorm"
	"gitlab.gaodun.com/golib/gderror"
	"permission/config"
	"permission/vigo_loger"
)

type NavigationFactory struct {
	Table        Tpo_Sys_Navigations
	engine       *xorm.Engine
	RowsSlicePtr []Tpo_Sys_Navigations
	UserNaviPtr  []UserNavigation
}

// 返回 user factory
func NewNavigationFactory() *NavigationFactory {
	funcFac := NavigationFactory{}
	funcFac.engine, _ = config.InitEng()

	return &funcFac
}

func (ntf *NavigationFactory) FindInfoByAppId(appId int32) error {
	if appId == 0 {
		return errors.New("appId is null")
	}

	err := ntf.engine.Where(" AppId = ? ", appId).OrderBy("SortNo").Find(&(ntf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}

// 用户
func (ntf *NavigationFactory) FindInfoUser(appId int32, userId int64) error {
	return ntf.engine.Join("INNER", "Tpo_Sys_User_Navigations", "Tpo_Sys_User_Navigations.NavigationId = Tpo_Sys_Navigations.NavigationId").Where("Tpo_Sys_User_Navigations.UserId=? and Tpo_Sys_Navigations.AppId=?", userId, appId).Find(&(ntf.UserNaviPtr))
}

// 角色查询菜单
func (ntf *NavigationFactory) FindInfoByRoles(roleIds []int64) error {
	ntf.RowsSlicePtr = []Tpo_Sys_Navigations{}
	if len(roleIds) == 0 {
		return errors.New("role id is null")
	}
	err := ntf.engine.Join("INNER", "Tpo_Sys_Role_Navigations", "Tpo_Sys_Navigations.NavigationId = Tpo_Sys_Role_Navigations.NavigationId").In("Tpo_Sys_Role_Navigations.RoleId", roleIds).Find(&(ntf.RowsSlicePtr))
	if err != nil {
		vigo_loger.AddGrayLog(gderror.New(err.Error()).Error())
	}

	return err
}
